import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/goods/goods_details_page.dart';
import 'package:gzmall_app/goods/goods_list_item_widget.dart';
import 'package:gzmall_app/model/product.dart';

class HomeGoodsListPage extends StatefulWidget {
  String page;
  String pageTitle;
  String params;

  HomeGoodsListPage(this.page, this.pageTitle, {this.params});

  @override
  State<StatefulWidget> createState() =>
      HomeGoodsListPageState(this.page, this.pageTitle, params: this.params);
}

class HomeGoodsListPageState extends State<HomeGoodsListPage> {
  String page;
  String pageTitle;
  String params;
  List<Product> spus = [];
  double _itemWidth;

  int _curPage = 1;
  RefreshListView _refreshListView;
  String _emptyTips = '商品在马不停蹄赶来';
  bool _showEmpty = false;

  HomeGoodsListPageState(this.page, this.pageTitle, {this.params});

  void init() {
    var size = MediaQuery.of(context).size;
    _itemWidth = (size.width - 12) / 2;
  }

  @override
  void initState() {
    super.initState();
    _getProductList(page == "yan_xuan_page", page == "day_goods_page",
        page == "activity_page", 1);
  }

  @override
  Widget build(BuildContext context) {
    init();
    return Scaffold(
        appBar: _createAppBar(),
        body: Container(
          color: ColorCommon.grey2,
          child: Column(children: <Widget>[
            Expanded(
              child: _buildGoodList(context),
            ),
          ]),
        ));
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text(pageTitle ?? ""),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  Widget _buildGoodList(BuildContext context) {
    _refreshListView = RefreshListView(
      enablePullUp: true,
      enablePullDown: true,
      onRefresh: _onRefresh,
      child: _buildGirdList(),
      emptyTips: _emptyTips,
      showEmpty: _showEmpty,
      onReload: () {
        _getProductList(page == "yan_xuan_page", page == "day_goods_page",
            page == "activity_page", 1);
      },
    );
    return _refreshListView;
  }

  Widget _buildGirdList() {
    List<Widget> spuList = spus
        .map((item) => new InkWell(
              child: new GoodsListItemWidget(item, _itemWidth),
              onTap: () {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new GoodsDetailsPage(productId: item.id);
                }));
              },
            ))
        .toList();
    return GridView.count(
      shrinkWrap: true,
      padding: const EdgeInsets.only(left: 4.0, right: 4.0, top: 4.0),
      crossAxisSpacing: 4.0,
      mainAxisSpacing: 4.0,
      controller: new ScrollController(keepScrollOffset: false),
      crossAxisCount: 2,
      childAspectRatio: 0.65,
      children: spuList,
    );
  }

  void _onRefresh(bool up) {
    if (up) {
      _getProductList(page == "yan_xuan_page", page == "day_goods_page",
          page == "activity_page", 1);
    } else {
      _getProductList(page == "yan_xuan_page", page == "day_goods_page",
          page == "activity_page", _curPage + 1);
    }
  }

  _getProductList(
      bool handpick, bool dayProduct, bool promotion, int page) async {
    bool isGetNew = page == 1;
    Map<String, Object> params = {"page": page.toString()};
    if (handpick) {
      params["handpick"] = handpick.toString();
    }
    if (promotion) {
      params["promotion"] = promotion.toString();
    }
    if (this.params != null && this.params.isNotEmpty) {
      Map<String, dynamic> otherParams = json.decode(this.params);
      params.addAll(otherParams);
    }
    NetUtil.get(
        context,
        Api.spus,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Product.fromJson(e))
              ?.toList();
          setState(() {
            _showEmpty =
                isGetNew && (_dataList == null || _dataList.length <= 0);
            _emptyTips = '没有符合条件的商品';
            if (isGetNew) {
              spus = _dataList;
            } else {
              spus.addAll(_dataList);
            }
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            _showEmpty = isGetNew && (spus == null || spus.length <= 0);
            _emptyTips = '没有符合条件的商品';
          });
          if (_refreshListView != null) {
            _refreshListView.refreshCompleted(isGetNew);
          }
        });
  }
}
